package com.zhan.drugStore.handler;

import com.zhan.drugStore.enums.ResultEnum;
import com.zhan.drugStore.exception.BusinessException;
import com.zhan.drugStore.util.ResponseBase;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;


@ControllerAdvice
public class ControllerExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    /**
     * 服务端异常
     */
    @ExceptionHandler(value = Exception.class)
    public @ResponseBody
    ResponseBase exceptionHandler(Exception ex) {
        LOGGER.error("服务端发生异常{}", ex.getMessage());
        return new ResponseBase().fail(ResultEnum.ERR_NETWORK_NULL);
    }

    /**
     * 权限异常
     */
    @ExceptionHandler(UnauthorizedException.class)
    public @ResponseBody
    ResponseBase authorizationExceptionHandler() {
        return new ResponseBase().fail(ResultEnum.ERR_NO_PERMISSION);
    }

    /**
     * 处理自定义异常返回
     */
    @ExceptionHandler(value = BusinessException.class)
    public @ResponseBody
    ResponseBase designerExceptionHandler(BusinessException ex) {
        return new ResponseBase().fail(ex.getCode(), ex.getMessage());
    }

    /**
     * 处理请求参数格式错误
     */
    @ExceptionHandler({BindException.class,ConstraintViolationException.class,HttpMessageNotReadableException.class,MethodArgumentNotValidException.class})
    public @ResponseBody
    ResponseBase paramValidExceptionHandler() {
        return new ResponseBase().fail(ResultEnum.ERR_PARAM_ERROR);
    }

}
